import KaseoDeviceInterface from "../KaseoDeviceInterface";

export const KASEO_DEV_KEYBOARD_GI: symbol = Symbol('Dev::Keyboard')

export type KaseoCommonKDI = {
    getKeyState: (keyId: number) => boolean
    getKeyDown: (keyId: number) => boolean
}

export default class extends KaseoDeviceInterface {
    private keyStates = new Array(256)
    private keyDownStates = new Array(256)
    
    constructor() {
        super(KASEO_DEV_KEYBOARD_GI, 'Dev::KaseoKeyboard')
    }

    $$devSetup(): void {
        this.writeMem(0, this.keyStates)
    }

    setKeyState(id: number, state: boolean) {
        if (id < 0 || id >= this.keyStates.length) {
            console.warn(`Kaseo-KayboardDI: key state id: ${id} > 255`)
            return
        }
        
        this.keyDownStates[id] = state
        this.keyStates[id] = state
        this.knockHost()
    }

    getKeyState(keyId: number): boolean {
        if (keyId < 0 || keyId >= this.keyStates.length)
            return false

        return this.keyStates[keyId]
    }

    getKeyDown(id: number): boolean {
        if (id < 0 || id >= this.keyDownStates.length) {
            console.warn(`Kaseo-KayboardDI: key state id: ${id} > 255`)
            return false
        }

        const state = this.keyDownStates[id]
        if (state == true)
            this.keyDownStates[id] = false
        return state
    }
}

